<!DOCTYPE html>
<html lang="en">
<head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
</head>
<body>
      <script>
   // AJAX => 发送http请求， 接收 http 响应, formate=> 对象拼接成符合规则的字符串;
            function formate( url , data ){
                  // 拼接字符串分成哪两种 : GET , POST ;
                  // 怎么去分辨 GET 和 POST 拼接 ?
                  // POST : 没有 url
                  // GET  : 有 url; 
                  var type = "GET";
                  if( arguments.length === 1){
                        // 此时为post请求的拼接;
                        type = "POST";
                        // 初始化数据 : 因为此时传入的参数只有一个，所以我们要补齐剩余参数;
                        data = url;
                        url = "";
                  }
                  // 拼接 : 
                  var start = true;
                  for(var key in data){
                        if( type === "GET"){
                              url += (start ? "?" : "&") + key + "=" + data[key];
                        }else if(type === "POST"){
                              url += (start ? "" : "&") + key + "=" + data[key];
                        }
                        start = false;
                  }
                  return url;
            }
            function ajax( method , url , _callback , data ){
                  if(method === "jsonp"){
                        // 为了防止报错加入 默认参数;
                        data = data || {};
                        data.jsonpcallback = data.jsonpcallback ? data.jsonpcallback : "callback";
                        // 请求发送;
                        var script = document.createElement("script");
                        script.src = formate( url , data );
                        document.body.appendChild( script );
                        window[data.jsonpcallback] = function( data ){
                              _callback(data);
                        }
                        script.onload = function(){
                              script.remove();
                        }
                  }else{
                        var xhr = new XMLHttpRequest();
                        xhr.open( method , method.toUpperCase() === "GET" ? formate( url , data ) : url );
                        if( method.toUpperCase() === "POST"){
                              xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
                        }
                        xhr.send( method.toUpperCase() === "POST" ? formate( data ) : null );
                        xhr.onreadystatechange = function(){
                              if( xhr.readyState === 4 && /^2\d{2}/.test(xhr.status)){
                                    callback( xhr.responseText )
                              }
                        }
                  }
            }
            ajax("jsonp","https://api.gogoup.com/p1/data/recommend",function(data){
                  console.log(data);
            })

      </script>